package com.example.samples.service.impl;

import com.example.samples.Vo.Page;
import com.example.samples.Vo.SamplePage;
import com.example.samples.bean.Sample;
import com.example.samples.mapper.SampleMapper;
import com.example.samples.service.SamplesService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
import java.util.UUID;


@Service
public class SamplesServiceImpl implements SamplesService {

  private   SampleMapper sampleMapper;

    public SamplesServiceImpl(SampleMapper sampleMapper) {
        this.sampleMapper = sampleMapper;
    }

    @Override
    public PageInfo findAll(SamplePage page) {
        PageHelper.startPage(page.getPageIndex(),page.getPageNumber());
        List<Sample>  sampleList=sampleMapper.findAll(page);


        PageInfo<Sample>  pageInfo=new PageInfo<Sample>(sampleList);
        return pageInfo;
    }

    @Override
    public Sample findById(Integer id) {
        return sampleMapper.findById(id);
    }

    @Override
    public int save(Sample sample) {
        return sampleMapper.save(sample);
    }

    @Override
    public int deleteById(Integer id) {
        return sampleMapper.deleteById(id);
    }


    @Override
    public int update(Sample sample,String path) {
      Sample  sa=sampleMapper.findById(sample.getId());
        if(sa.getFilePath()==null){
            sa.setFilePath("");
        }
      if (!sa.getFileName().equals(sample.getFileName())){
          String suffix = sa.getName().substring(sa.getName().lastIndexOf("."), sa.getName().length());
          String uuid = UUID.randomUUID().toString();
          for (int i = 0; i < sa.getFileNumber(); i++) {
              String name = sa.getName().substring(0, sa.getName().lastIndexOf("."));
              String fileName = path + sa.getFilePath() + "/" + name + "_" + i + suffix;
              File file = new File(fileName);
              //将原文件更改为f:\a\b.xlsx，其中路径是必要的。注意
              file.renameTo(new File(path + sa.getFilePath() + "/" + uuid + "_" + sample.getFileName() + "_" + i + suffix));
          }
          String name = uuid + "_" + sample.getFileName() + suffix;
          sample.setName(name);
      }
        return sampleMapper.update(sample);
    }


}
